var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser = require('body-parser');

var multipart = require('connect-multiparty');

var mysql = require('mysql');
var db = require('./public/javascripts/db');
var async = require('async');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var uploadRouter = require('./routes/upload');
var screeningRouter = require('./routes/screening');
var historyRouter = require('./routes/history');
var resultRouter = require('./routes/detail');
var itemRouter = require('./routes/item');
var loginRouter = require('./routes/login');
var registerRouter = require('./routes/register');
var mailRouter = require('./routes/mail');
var screeningNewRouter = require('./routes/screeningNew');
var testRouter = require('./routes/test');
var resultsRouter = require('./routes/result');
var detailNewRouter = require('./routes/detailNew');
var medicalNumRouter = require('./routes/medicalNum');
var screening2Router = require('./routes/screening2');
var screeningListRouter = require('./routes/screeningList');
var image2Router = require('./routes/image2');
var tasksRouter = require('./routes/tasks');
var diagnosticOpinionRouter = require('./routes/addDiagnosticOpinion');

var app = express();
var token = require('./public/javascripts/utils');
var imgUploadPath = require('./public/javascripts/config').imgUploadPath;
// const jwt = require('jsonwebtoken');
// const fs = require('fs');

// function verifyToken(token) {
//     let cert = fs.readFileSync(path.join(__dirname, './public/rsa_public_key.pem'));
//     try {
//         let result = jwt.verify(token, cert, {algorithms: ['RS256']}) || {};
//         // console.log('verifyToken', result)
//         let {exp = 0} = result, current = Math.floor(Date.now() / 1000);
//         if (current <= exp) {
//             res = result.data || {};
//         }
//     } catch (e) {
//         // console.log('e', e);
//         res = 'err'
//     }
//     return res;
// }

//跨域设置
app.use(cors({
    // origin: ['http://localhost:8080', 'http://localhost:8081'],  //开发环境跨域配置
    origin: ['http://192.168.1.103', 'http://192.168.1.114:8080', 'http://localhost',
        'http://localhost:8080', 'http://localhost:8081'],  //本地生产环境跨域配置
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    alloweHeaders: ['Content-Type', 'Authorization']
}));

//上传图片存放路径
// app.use(multipart({uploadDir: '/Users/michaelshan/Desktop/imageUpload'}))
app.use(multipart({uploadDir: imgUploadPath}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));


//token验证
app.use((req, res, next) => {
    // console.log(req.url, req.headers);
    // console.log(req.headers);
    if (req.headers.referer.split(':').pop() == '8080/') {
        next()
    } else {
        if (req.url != '/login' && req.url != '/register' && req.url != '/mail' && req.url != '/detail') {
            var result = token.verifyToken(req.headers.token);
            if (result == 'err') {
                console.log('登陆已过期');
                res.send({status: 403, msg: '登陆已过期'})
            } else {
                next();
            }
        } else {
            next()
        }
    }
})

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/upload', uploadRouter);
app.use('/screening', screeningRouter);
app.use('/getHistory', historyRouter);
app.use('/getResult', resultRouter);
app.use('/getId', itemRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter);
app.use('/mail', mailRouter);
app.use('/screeningNew', screeningNewRouter);
app.use('/test', testRouter);
app.use('/result', resultsRouter);
app.use('/detail', detailNewRouter);
app.use('/medicalNum', medicalNumRouter);
app.use('/screening2', screening2Router);
app.use('/screeningList', screeningListRouter);
app.use('/image2', image2Router);
app.use('/tasks', tasksRouter);
app.use('/addOpinion', diagnosticOpinionRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

// var connection = mysql.createConnection({
//     host: 'localhost',
//     user: 'root',
//     password: 'shanxi921017',
//     database: 'RUNOOB'
// });
//
// connection.connect();
//
// db.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
//     if (error) throw error;
//     console.log('The solution isisis: ', results[0].solution);
// });

// const addSql = 'insert runoob_tbl (runoob_id,runoob_title,runoob_author,submission_date) values(?,?,?,?)';
// const addSqlParams = [9999, "孙", "man", '2018-07-08'];
//
// connection.query(addSql, addSqlParams, function (err, result) {
//     if (err) {
//         console.log('[INSERT ERROR] - ', err.message);
//         return;
//     }
//
//     console.log('INSERT ID:', result);
// });

var sql = {
    'sql1': 'create table if not exists users(' +
    'id int not null auto_increment,' +
    'phone varchar(255),' +
    'name varchar(255),' +
    'identify_num varchar(255),' +
    'gender varchar(255),' +
    'age varchar(255), ' +
    'birth_place varchar(255), ' +
    'birth_date varchar(255), ' +
    'medical_history varchar(255), ' +
    'locked varchar(255), primary key (id))',
    'sql2': 'create table if not exists images(' +
    'id int not null auto_increment,' +
    'location varchar(255), ' +
    'owner_id int, ' +
    'load_by varchar(255), ' +
    'load_time varchar(255), ' +
    'type int, medical_num varchar(255), new_medical_num varchar(255),primary key(id))',
    'sql3': 'create table if not exists tasks (' +
    'id int not null auto_increment,' +
    'img_id varchar(255),' +
    'user_id varchar(255),' +
    'owner_id varchar(255),' +
    'algorithm varchar(255),' +
    'status int,' +
    'start_time varchar(255),' +
    'end_time varchar(255), primary key (id))',
    'sql4': 'create table if not exists results (' +
    'id int not null auto_increment,' +
    'img_id varchar(255),' +
    'user_id varchar(255),' +
    'owner_id varchar(255),' +
    'isDr double,' +
    'vessel varchar(255),' +
    'mass_vessel varchar(255), odlocation varchar(255),created_time varchar(255),' +
    'medical_num varchar(255), diagnostic_opinion text(65535),primary key (id))',
    'sql5': 'create table if not exists user(' +
    'id int not null auto_increment,username varchar(255),' +
    'password varchar(255),mail varchar(255),primary key (id))'
}
var tasks = ['sql1', 'sql2', 'sql3', 'sql4', 'sql5'];
async.eachSeries(tasks, (item, callback) => {
    db.query(sql[item], (err, result) => {
        // console.log('sql result', result);
        callback(err, result);
    })
}, (err) => {
    console.log('err', err)
})


module.exports = app;
